#include <stdio.h>
#include "redisop.h"

CRedisOp::CRedisOp()
{
	m_redis = NULL;
	m_ConnStatus = false;
	m_serverInfo = NULL;
}

CRedisOp::~CRedisOp()
{
	if( this->m_redis!=NULL )
	{
		credis_close(this->m_redis);
		this->m_redis=NULL;
	}
}

void CRedisOp::SetInfo(void * args)
{
	this->m_serverInfo = args;
	this->m_ConnStatus = true;
}

bool CRedisOp::GetStatus()
{
	return this->m_ConnStatus;
}

void CRedisOp::SetStatusFail()
{
    this->m_ConnStatus = false;
}

bool CRedisOp::ReConnect()
{
    if( this->m_ConnStatus ) return true;

    ServerInfo * sinfo = (ServerInfo*)this->m_serverInfo;

    this->m_redis = credis_connect(sinfo->szIp, sinfo->iPort, 10000);
    if (this->m_redis == NULL) 
    {
        printf("Error connecting to Redis server. Please start server to run tests.\n");
        this->m_ConnStatus = false;
        return false;
    }
	this->m_ConnStatus = true;

	return true;
}

bool CRedisOp::Init(void * args)
{
	this->SetInfo( args );
	ServerInfo * sinfo = (ServerInfo*)this->m_serverInfo;
	if( this->m_redis==NULL )
	{
		this->m_redis = credis_connect(sinfo->szIp, sinfo->iPort, 10000);

		if (this->m_redis == NULL) 
		{
			printf("Error connecting to Redis server. Please start server to run tests.\n");
			this->m_ConnStatus = false;
			return false;
		}
	}
	return true;
}

int CRedisOp::SetDataTest(const char * key, const char * val)
{
    int iRet = 0;

    if( key==NULL )
	{
        printf( "Set key is NULL.\n" );
        return -1;
	}

    iRet = credis_set( this->m_redis, key, val);
    
    if( iRet==0 )
    {
        this->SetKeepAlive( key, 5184000 ); //default set 60 days=60*24*60*60
    }
    else
    {
        printf( "Set key data fail.\n" );
    }

    return iRet;
}

/*
 * return value: -1 -> key null
 *               -2 -> other error
 * */
int CRedisOp::SetData(const char * key, const char * val, unsigned int iValueLen)
{
    int iRet = 0;

    if( key==NULL )
	{
        printf( "Set key is NULL.\n" );
        return -1;
	}

    iRet = credis_set_hc( this->m_redis, key, val, iValueLen );
    
    if( iRet==0 )
    {
        this->SetKeepAlive( key, 5184000 ); //default set 60 days=60*24*60*60
    }
    else
    {
        printf( "Set key data fail.\n" );
    }

    return iRet;
}

void CRedisOp::SetKeepAlive( const char * key, int iTimeOut )
{
	if( key!=NULL )
	{
		credis_expire( this->m_redis, key, iTimeOut ); //default timeout 30 minutes
	}
}
int CRedisOp::GetResult( const char * key, char ** vResult )
{
	int rc;

	rc = credis_get(this->m_redis, key, vResult);
	if( rc<0 )
	{
		printf( "get kalle returned fail.\n" );
		return rc;
	}

	printf("get kalle returned: %s\n", *vResult);

	return rc;
}

